<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="90px">
          <el-col :span="6">
            <el-form-item  label="客户名称">
              <el-select v-model="listQuery.fsiteNo" 
              v-if="this.$store.state.user.fsiteLevel==3"
              disabled clearable filterable class="filter-item" placeholder="请选择客户名称">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-model="listQuery.fsiteNo" 
              v-else
              clearable filterable class="filter-item" placeholder="请选择客户名称" @change="getFpointOptions(listQuery.fsiteNo)">
          <el-option
            v-for="item in fsiteNoBelongOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实验楼">
        <el-select v-model="listQuery.fpointNo" clearable filterable class="filter-item" placeholder="请选择实验楼">
          <el-option
            v-for="item in fpointOptions2"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实验楼类型">
        <el-select v-model="listQuery.fpointFlag" clearable class="filter-item" placeholder="请选择实验楼类型">
          <el-option v-for="(key, value) in siteTypeMap" :key="key" :label="key" :value="value"/>
        </el-select>
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
        <el-button type="primary" @click="handleFilter">查找</el-button>
        <el-button type="success" @click="handleCreate">添加</el-button>
      </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
       <JNPF-table v-loading="listLoading"  :data="list" >
      <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序" type="index"/>
      <el-table-column :formatter="formatSite" align="left" label="客户名称" prop="fsiteNo"/>
      <el-table-column align="left" label="实验楼编号" prop="fpointNo"/>
      <el-table-column align="left" label="实验楼名称" prop="fpointName"/>
      <el-table-column align="left" label="实验楼类型" prop="fpointFlag">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.fpointFlag | siteTypeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :width="buttonColor.state" align="left" label="状态" prop="fpointState">
        <template slot-scope="scope">
          <span v-if="scope.row.fpointState===0" :style="{color:buttonColor.statedisable}">{{ scope.row.fpointState | statusFilter }}</span>
          <span v-else :style="{color:buttonColor.statestart}">{{ scope.row.fpointState | statusFilter }}</span>
        </template>
      </el-table-column>
    </JNPF-table>
    <paginations
      :total="total"
        :page.sync="listQuery.currentPage"
        :limit.sync="listQuery.pageSize"
       />
      </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="50%">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="95px" ref="dataForm" :rules="rules" :model="dataForm">
          <el-col :span="12">
            <el-form-item label="实验楼编号" prop="fpointNo">
              <el-input v-model="dataForm.fpointNo" :disabled="dialogStatus==='update'" type="number"/><!-- oninput="value=value.replace(/[^\d]/g,'')"-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item  label="客户名称" prop="fsiteNo">
              <el-select  v-if="this.$store.state.user.fsiteLevel==3" v-model="dataForm.fsiteNo" disabled clearable filterable placeholder="请选择" @change="getStations(dataForm.fsiteNo, true)">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-else v-model="dataForm.fsiteNo" :disabled="dialogStatus=='update'" clearable filterable placeholder="请选择" @change="getStations(dataForm.fsiteNo, true)">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item  label="实验楼名称" prop="fpointName">
              <el-input v-model="dataForm.fpointName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="el-form-item-small" label="实验楼类型" prop="fpointFlag">
              <el-select v-model="dataForm.fpointFlag" :disabled="dialogStatus=='update'" clearable class="filter-item" placeholder="请选择实验楼类型">
                <el-option v-for="(key, value) in siteTypeMap" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="fpointL">
              <el-input v-model="dataForm.fpointL"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="fpointD">
              <el-input v-model="dataForm.fpointD"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高度" prop="fpointH">
              <el-input v-model="dataForm.fpointH" @focus="pop3(dataForm.fsiteNo,dataForm.fparentNo)"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宽度" prop="fpointW">
              <el-input v-model="dataForm.fpointW" @focus="pop3(dataForm.fsiteNo,dataForm.fparentNo)"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-show="dataForm.fpointFlag==2" label="图片(2M内)" prop="fimage">
              <el-upload
                v-model="dataForm.fimage"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadPath"
                :data="formdata2(dataForm.fpointNo)"
                class="avatar-uploader">
                <img v-if="dataForm.fimage" :src="dataForm.fimage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="el-form-item-small" label="状态" prop="fpointState">
              <el-select v-model="dataForm.fpointState" class="filter-item" placeholder="请选择状态">
                <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" v-if="dialogStatus=='create'" @click="createData">确定</el-button>
        <el-button v-else type="primary"  @click="updateData">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'
import { listRoom, createRoom, updateRoom, deleteRoom } from '@/api/room'
import { uploadPath2 } from '@/api/area'
import { getToken } from '@/utils/auth'
import { getApiUrl } from '@/utils/request'
import { fsiteOptionsByLevel, fpointOptions, fpointOptions2 } from '@/api/area'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { uploadPath } from '@/api/room'
import cmap from './baiduMap'
import { listPointByFsiteNo2 } from '@/api/airAlarm'
import { tableColor, titleColor, buttonColor, exportColor } from '@/filters/index'

const siteTypeMap = {
  1: '室外',
  2: '室内总站'
}

const statusMap = {
  0: '禁用',
  1: '启用'
}

export default {
  name: 'Room',
  components: { Pagination, cmap },
  filters: {
    siteTypeFilter(type) {
      return siteTypeMap[type]
    },
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      uploadVisible: false,
      downUrl: null,
      exportColor,
      uploadPath,
      uploadPath2,
      list: null,
      total: 0,
      fsiteNoBelongOptions: null,
      fpointOptions: null,
      fpointOptions2: null,
      imgUrl: null,
      center: '北京',
      lat: 0,
      lng: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteNo: undefined,
        fpointNo: undefined,
        fimage: undefined,
        fparentNo: undefined,
        fpointFlag: undefined,
        fpointState: 2,
        sort: 'create_time',
        order: 'desc'
      },
      siteTypeMap,
      statusMap,
      dataForm: {
        id: undefined,
        fpointNo: undefined,
        fimage: undefined,
        fpointName: undefined,
        fsiteNo: undefined,
        fparentNo: undefined,
        fpointFlag: undefined,
        fpointL: undefined,
        fpointD: undefined,
        fpointH: undefined,
        fpointW: undefined,
        fpointState: undefined,
        fupddate: undefined,
        foperator: undefined
      },
      eqtActionOptions: [],
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableColor: tableColor,
      titleColor: titleColor,
      buttonColor: buttonColor,
      rules: {
        fpointNo: [
          { required: true, message: '监测点编号不能为空', trigger: 'blur' }
        ],
        fpointName: [
          { required: true, message: '监测点名称不能为空', trigger: 'blur' }
        ],
        fsiteNo: [
          { required: true, message: '客户名称不能为空', trigger: 'blur' }
        ],
        // fparentNo: [
        //   { required: true, message: '上级监测点编号不能为空', trigger: 'blur' }
        // ],
        fpointFlag: [
          { required: true, message: '监测点类型不能为空', trigger: 'blur' }
        ],
        fpointState: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      },
      permissionDialogFormVisible: false,
      systemPermissions: null,
      assignedPermissions: null,
      permissionForm: {
        roleId: undefined,
        permIds: []
      }
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  created() {
    this.downUrl = getApiUrl() + 'xlsx/1-7实验楼.xlsx'
    if (this.$store.state.user.fsiteLevel == 3) {
      this.listQuery.fsiteNo = this.$store.state.user.fsiteNo
      fpointOptions2(this.$store.state.user.fsiteNo)
        .then(response => {
          this.fpointOptions2 = response.data.data.list
        })
        .catch(() => {
          this.fpointOptions2 = []
        })
    }
    this.getList()
    fsiteOptionsByLevel(3)
      .then(response => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
      .catch(() => {
        this.fsiteNoBelongOptions = []
      })
  },
  methods: {

    // 导入
    uploadFileSuccess: function(response) {
      this.uploadVisible = false
      this.$notify.success({
        title: '导入',
        dangerouslyUseHTMLString: true,
        message: response.data
      })
    },
    handleUpload() {
      this.uploadVisible = true
    },
    /** *
     * 图片点击事件。
     */
    getClickInfo(e) {
      document.getElementById('span').style.setProperty('left', (e.offsetX - 20).toString() + 'px')
      document.getElementById('span').style.setProperty('top', (e.offsetY - 25).toString() + 'px')
    },
    setPosition() {
      this.dialogFormVisible3 = false
      var a = document.getElementById('image')
      this.dataForm.fpointH = a.clientHeight
      this.dataForm.fpointW = a.clientWidth
      this.dataForm.fpointD = document.getElementById('span').style.getPropertyValue('left').replace('px', '')
      this.dataForm.fpointL = document.getElementById('span').style.getPropertyValue('top').replace('px', '')
      this.$refs['dataForm'].validateField('fpointL')
      this.$refs['dataForm'].validateField('fpointD')
      this.$refs['dataForm'].validateField('fpointH')
      this.$refs['dataForm'].validateField('fpointW')
    },
    pop3(fsiteNo, fparentNo) {
      if ((fparentNo === undefined || fparentNo === null || fparentNo === '' || fparentNo === '0') && (fsiteNo === undefined || fsiteNo === null || fsiteNo === '')) {
        this.$notify.info({
          message: '请先选择 客户名称 或 上级监测点'
        })
        return
      }
      if (fparentNo === undefined || fparentNo === null || fparentNo === '' || fparentNo === '0') { // 教学楼
        // this.imgUrl = 'air/images/002/site/' + fsiteNo + '.png'
        this.imgUrl = '300003.png'
      } else { // 教室
        this.imgUrl = 'air/images/002/indoor/' + fparentNo + '.png'
      }
      var that = this
      $.ajax({
        type: 'get',
        // url: 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png',
        // url: this.imgUrl,
        url: '300003.png',
        success: function(data) {
          that.dialogFormVisible3 = true
        },
        error: function(data) {
          return
        }
      })
    },
    formdata2: function(fpointno) {
      // const formdata = new FormData()
      // formdata.append('fpointno', '123456')
      return { 'ftype': '1', 'fpointno': fpointno }
    },
    handleAvatarSuccess(res, file) {
      // this.dataForm.fimage = URL.createObjectURL(file.raw)
      this.dataForm.fimage = res.data
      const time = new Date().getTime()
      this.dataForm.fimage = `${this.dataForm.fimage}?time=${time}`
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M // isJPG &&
    },
    formatStatus: function(row, column) {
      return row.fpointState === 1 ? '启用' : '禁用'
    },
    dateFormat(row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    formatSite: function(row, column) {
      if (this.fsiteNoBelongOptions) {
        for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
          if (row.fsiteNo === this.fsiteNoBelongOptions[i].value) {
            return this.fsiteNoBelongOptions[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    getFpointOptions(fsiteNo) {
      this.listQuery.fpointNo = undefined
      this.listQuery.fparentNo = undefined
      this.fpointOptions = []
      this.fpointOptions2 = []
      if (fsiteNo) {
        fpointOptions(fsiteNo)
          .then(response => {
            this.fpointOptions = response.data.data.list
          })
          .catch(() => {
            this.fpointOptions = []
          })
        fpointOptions2(fsiteNo)
          .then(response => {
            this.fpointOptions2 = response.data.data.list
          })
          .catch(() => {
            this.fpointOptions2 = []
          })
      }
    },
    getStations(fsiteNo, clearFparentNo) {
      this.eqtActionOptions = []
      if (clearFparentNo) {
        this.dataForm.fparentNo = ''
      }
      if (fsiteNo) {
        listPointByFsiteNo2(fsiteNo)
          .then(response => {
            this.eqtActionOptions = response.data.data.list
          })
          .catch(() => {
            this.eqtActionOptions = []
          })
      }
    },
    getList() {
      this.listLoading = true
      if (this.listQuery.fpointFlag) {
        listRoom(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      } else {
        const remp = {
          page: this.listQuery.page,
          limit: this.listQuery.limit,
          fsiteNo: this.listQuery.fsiteNo,
          fpointNo: this.listQuery.fpointNo,
          fimage: this.listQuery.fimage,
          fparentNo: this.listQuery.fparentNo,
          fpointFlag: '3',
          fpointState: 2,
          sort: this.listQuery.sort,
          order: this.listQuery.order
        }
        listRoom(remp)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        fpointNo: undefined,
        fimage: undefined,
        fpointName: undefined,
        fsiteNo: undefined,
        fparentNo: undefined,
        fpointFlag: undefined,
        fpointL: undefined,
        fpointD: undefined,
        fpointH: undefined,
        fpointW: undefined,
        fpointState: undefined,
        fupddate: undefined,
        foperator: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.dataForm.fpointState = '1'
      this.dataForm.fpointFlag = '2'
      if (this.$store.state.user.fsiteLevel == 3) {
        this.dataForm.fsiteNo = this.$store.state.user.fsiteNo
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    clickMap() {
      // this.resetForm()
      this.dialogFormVisible2 = true
      this.lat = 0
      this.lng = 0
      // this.dataForm.fsiteState = '1'
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    getPoint(point) {
      this.lat = point.lat
      this.lng = point.lng
    },
    setLatLng() {
      this.dialogFormVisible2 = false
      this.dataForm.fpointL = this.lat
      this.dataForm.fpointD = this.lng
      this.$refs['dataForm'].validateField('fpointL')
      this.$refs['dataForm'].validateField('fpointD')
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          this.dataForm.fparentNo = 0
          createRoom(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dataForm.fpointFlag = row.fpointFlag.toString()
      this.dataForm.fpointState = row.fpointState.toString()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getStations(row.fsiteNo, false)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          updateRoom(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fpointNo === this.dataForm.fpointNo) {
                  const index = this.list.indexOf(v)
                  this.dataForm.fpointState = parseInt(this.dataForm.fpointState)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否删除该资料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRoom(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>